//
//  WebLodingController.m
//  New_Runway
//
//  Created by mack on 2018/1/25.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "WebLodingController.h"
@interface NSURLRequest (InvalidSSLCertificate)

+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;

@end
@interface WebLodingController ()<WKScriptMessageHandler>
@property (nonatomic, strong) NSURLRequest *request;
//判断是否是HTTPS的
@property (nonatomic, assign) BOOL isAuthed;

//返回按钮
@property (nonatomic, strong) UIButton *backItem;
//关闭按钮
@property (nonatomic, strong) UIButton *closeItem;

//下面的三个属性是添加进度条的
@property (nonatomic, assign) BOOL theBool;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation WebLodingController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBarView.leftItem.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    self.wkwebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, self.navH, self.view.frame.size.width, self.view.frame.size.height - self.BotH - self.navH )];
    self.wkwebView.navigationDelegate = self;
    [self.view addSubview:self.wkwebView];
    
    [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"Share"];
    [self addLeftButton];
    
    //添加进度条（如果没有需要，可以注释掉
    [self addProgressBar];
    self.navigationBarView.rightItem.hidden = YES;
}

//加载URL
- (void)loadHTML:(NSString *)htmlString
{
    NSURL *url = [NSURL URLWithString:htmlString];
    self.request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0];
    [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
    [self.wkwebView loadRequest:self.request];
    
}

#pragma mark - UIWebViewDelegate

//开始加载
//- (BOOL)webView:(UIWebView *)awebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
//{
//    NSURL *clickURL = request.URL;
//    _currUrl = clickURL.absoluteString;
//    NSString* scheme = [[request URL] scheme];
//    //判断是不是https
//    if ([scheme isEqualToString:@"https"]) {
//        //如果是https:的话，那么就用NSURLConnection来重发请求。从而在请求的过程当中吧要请求的URL做信任处理。
//        if (!self.isAuthed) {
//            NSURLConnection* conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//            [conn start];
//            [awebView stopLoading];
//            return NO;
//        }
//    }
//    return YES;
//}
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
   
    
//    if ([self.currUrl containsString:@"cars_detial.html"] || [self.currUrl containsString:@"home.html"]) {
        NSURLRequest *urlstr = navigationAction.request;
        _currUrl = [urlstr.URL absoluteString];
//    }
    
    NSString* scheme = [[navigationAction.request URL] scheme];
    if ([scheme isEqualToString:@"tel"]) {
        NSURLRequest *urlstr = navigationAction.request;
        NSString *tel = [urlstr.URL absoluteString];
        NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"%@",tel];
        UIWebView *callWebview = [[UIWebView alloc] init];
        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
        [self.view addSubview:callWebview];
    }
    
    if ([scheme isEqualToString:@"https"]) {
        //如果是https:的话，那么就用NSURLConnection来重发请求。从而在请求的过程当中吧要请求的URL做信任处理。
        if (!self.isAuthed) {
            NSURLConnection* conn = [[NSURLConnection alloc] initWithRequest:navigationAction.request delegate:self];
            [conn start];
            [webView stopLoading];
//            decisionHandler(YES);
        }
    }
     decisionHandler(YES);
}

//设置webview的title为导航栏的title
//- (void)webViewDidFinishLoad:(UIWebView *)webView
//{
//    self.theBool = true; //加载完毕后，进度条完成
//    self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
//
//
//}
#pragma mark ================= NSURLConnectionDataDelegate <NSURLConnectionDelegate>

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge previousFailureCount] == 0) {
        self.isAuthed = YES;
        //NSURLCredential 这个类是表示身份验证凭据不可变对象。凭证的实际类型声明的类的构造函数来确定。
        NSURLCredential *cre = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        [challenge.sender useCredential:cre forAuthenticationChallenge:challenge];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"网络不给力");
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.isAuthed = YES;
    //webview 重新加载请求。
    [self.wkwebView loadRequest:self.request];
    [connection cancel];
}

#pragma mark - 添加关闭按钮

- (void)addLeftButton
{
    [self.navigationBarView addSubview: self.backItem];
}

//点击返回的方法
- (void)backNative
{
    
    //判断是否有上一层H5页面
    if ([self.wkwebView canGoBack]) {
        //如果有则返回
        [self.wkwebView goBack];
        //同时设置返回按钮和关闭按钮为导航栏左边的按钮
       [self.navigationBarView addSubview:self.closeItem];
    } else {
        [self closeNative];
    }
}

//关闭H5页面，直接回到原生页面
- (void)closeNative
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - init

- (UIButton *)backItem
{
    if (!_backItem) {
        _backItem = [[UIButton alloc] init];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        //这是一张“<”的图片，可以让美工给切一张
        UIImage *image = [UIImage imageNamed:@"nav_common_back_n"];
        [btn setImage:image forState:UIControlStateNormal];
        //        [btn setTitle:@"返回" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(backNative) forControlEvents:UIControlEventTouchUpInside];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:17]];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        //字体的多少为btn的大小
//        [btn sizeToFit];
        //左对齐
//        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        //让返回按钮内容继续向左边偏移15，如果不设置的话，就会发现返回按钮离屏幕的左边的距离有点儿大，不;美观
        //        btn.contentEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0);
        btn.frame = CGRectMake(2, self.navH-44, 40, 44);
        _backItem = btn;
    }
    return _backItem;
}

- (UIButton *)closeItem
{
    if (!_closeItem) {
        
        _closeItem = [[UIButton alloc] init];
        [_closeItem addTarget:self action:@selector(closeNative) forControlEvents:UIControlEventTouchUpInside];
        [_closeItem setTitle:@"关闭" forState:UIControlStateNormal];
        [_closeItem setTitleColor:kColorWhite() forState:UIControlStateNormal];
        [_closeItem setFrame:CGRectMake(45, self.navH - 44, 40, 44)];


    }
    return _closeItem;
}

#pragma mark - 下面所有的方法是添加进度条

- (void)addProgressBar
{
    // 仿微信进度条
    CGFloat progressBarHeight = 0.5f;
//    CGRect navigationBarBounds = self.navigationBarView.bounds;
    CGRect barFrame = CGRectMake(0, self.navH, Screen_width, progressBarHeight);
    self.progressView = [[UIProgressView alloc] initWithFrame:barFrame];
    self.progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    self.progressView.trackTintColor = MAIN_NAV_COLOR(); //背景色
    self.progressView.progressTintColor = kColorWhite(); //进度色
    [self.view addSubview:self.progressView];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //移除progressView  because UINavigationBar is shared with other ViewControllers
    [self.progressView removeFromSuperview];
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {

    self.progressView.progress = 0;
    self.theBool = false;
    //0.01667 is roughly 1/60, so it will update at 60 FPS
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01667 target:self selector:@selector(timerCallback) userInfo:nil repeats:YES];
}
//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
    self.theBool = true; //加载完毕后，进度条完成
    //执行Js
    kSelfWeak;
    NSString *inputValueJS = @"document.title";
    //执行Js
    [webView evaluateJavaScript:inputValueJS completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"value: %@ error: %@", response, error);
        weakSelf.title = response;
    }];
//    NSString *funJs =[NSString stringWithFormat:@"callJS('%@')",@"iOS"] ;
//    [webView evaluateJavaScript:funJs completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//        NSLog(@"value: %@ error: %@", response, error);
//        weakSelf.title = response;
//    }];
}

//- (void)webViewDidStartLoad:(UIWebView *)webView
//{
//    self.progressView.progress = 0;
//    self.theBool = false;
//    //0.01667 is roughly 1/60, so it will update at 60 FPS
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01667 target:self selector:@selector(timerCallback) userInfo:nil repeats:YES];
//}

- (void)timerCallback
{
    if (self.theBool) {
        if (self.progressView.progress >= 1) {
            self.progressView.hidden = true;
            [self.timer invalidate];
        } else {
            self.progressView.progress += 0.1;
        }
    } else {
        self.progressView.progress += 0.1;
        if (self.progressView.progress >= 0.9) {
            self.progressView.progress = 0.9;
        }
    }
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    
    if ([message.name isEqualToString:@"Share"]) {
        
        self.shareTitle = message.body[@"title"];
        self.shareDesc = message.body[@"desc"];
        self.imageUrl = message.body[@"url"];
        if ([WXApi isWXAppInstalled]) {
            if ([self.mainTitle isEqualToString:@"微店预览"]) {
                //判断是否有微信
                [self.navigationBarView.rightItem setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
                self.navigationBarView.rightItem.hidden = NO;
            }else{
                self.navigationBarView.rightItem.hidden = YES;
                
            }
            
        }else{
            self.navigationBarView.rightItem.hidden = YES;
        }
    }
}

@end
